import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import qs from 'qs'
/**
 * @param 封装axios请求
 */
export default class Request {
  constructor() {
  }
  public static instance: AxiosInstance;
  public static init() {
    // 创建axios实例
    this.instance = axios.create({
      // baseURL: "http://112.74.164.157:7001",
      baseURL: "http://127.0.0.1:7001",
      // timeout: 6000,
    });
    // 初始化拦截器
    this.initInterceptors();
  }
  // 拦截器
  public static initInterceptors() {
    // 设置post请求头
    this.instance.defaults.headers.post["Content-Type"] =
      "application/x-www-form-urlencoded; charset=UTF-8";

    /**
     * @param 配置请求拦截器，如果本地存储存在token则携带过去
     */
    this.instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        // const token = store.getters.token
        const token = localStorage.getItem("ACCESS_TOKEN");
        if (token) {
          if (!config.headers) {
            config.headers = {};
          }
          config.headers.token = "Bearer " + token; // 请求头部添加token
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
    /**
     * @param 配置响应拦截器拦截器
     */
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        // 如果token为空的话则跳转到login页面中
        const code = response.status;
        if ((code >= 200 && code < 300) || code === 304) {
          return Promise.resolve(response.data);
        } else {
          return Promise.reject(response);
        }
      },
      (error) => {
        console.log(error);
        if (error.response) {
          switch (error.response.status) {
            case 401:
              ElMessage.error("用户无权限");
              localStorage.removeItem('ACCESS_TOKEN')
              location.reload()
              break;
            case 404:
              ElMessage.error("接口请求不存在");
              break;
            default:
              ElMessage.error(error.response.data.message);
          }
        } else {
          // 请求超时或者网络有问题
          if (error.message.includes("timeout")) {
            ElMessage.error("请求超时！请检查网络是否正常");
          } else {
            ElMessage.error("请求失败，请检查网络是否已连接");
          }
        }
        return Promise.reject(error);
      }
    );
  }
  // 封装post请求
  public static post(url: string, data: Object) {
    console.log(data, '===>', url);
    return this.instance({
      method: 'post',
      url,
      data: qs.stringify(data)
    })
  }
  // 封装上传图片请求
  public static upload(url: string, data: Object) {
    return this.instance({
      method: 'post',
      url,
      headers: {
        ["Content-Type"]: " multipart/form-data"
      },
      data
    })
  }
  // 封装get请求
  public static get(url: string, params: object = {}) {
    return this.instance({
      method: 'get',
      url,
      params
    })
  }
}
